#include "include/richtextview.h"

#include <QAbstractTextDocumentLayout>
#include <QPainter>
#include <QTextBlock>
#include <QTextBlockFormat>
#include <QTextCursor>


namespace
{
	class PaintDeviceSetter
	{
		public:

			PaintDeviceSetter(QTextDocument* pDoc, QWidget* newPaintDevice)
			{
				m_pDoc = pDoc;
				m_pSavedPaintDevice = m_pDoc->documentLayout()->paintDevice();
				m_pDoc->documentLayout()->setPaintDevice(newPaintDevice);
			}

			~PaintDeviceSetter()
			{
				m_pDoc->documentLayout()->setPaintDevice(m_pSavedPaintDevice);
			}

		private:

			QPaintDevice* m_pSavedPaintDevice;
			QTextDocument *m_pDoc;
	};
}


RichTextView::RichTextView(QWidget *parent) :
	QWidget(parent), m_pDocument(0), _contentIsVisible(true)
{
}


QTextDocument* RichTextView::document() const
{
	return m_pDocument;
}



void RichTextView::setDocument(QTextDocument* value)
{
	if (m_pDocument != 0)
	{
		disconnect(m_pDocument, SIGNAL(contentsChanged()), this, SLOT(update()));
	}

	m_pDocument = value;

	if (m_pDocument != 0)
	{
		connect(m_pDocument, SIGNAL(contentsChanged()), this, SLOT(update()));
	}

	update();
}


bool RichTextView::contentIsVisible() const
{
	return _contentIsVisible;
}


void RichTextView::setContentIsVisible(bool value)
{
	if (_contentIsVisible == value)
		return;

	_contentIsVisible = value;

	update();
}

void RichTextView::paintEvent(QPaintEvent* event)
{
	QPainter p(this);

	if (m_pDocument == 0 || !contentIsVisible())
		return;

	PaintDeviceSetter(m_pDocument, this);

	m_pDocument->setTextWidth(size().width());

	qreal documentHeight = document()->size().height();
	qreal activeAreaHeight = size().height();

	if (documentHeight < activeAreaHeight)
	{
		qreal dy = (activeAreaHeight - documentHeight) / 2.0;
		p.translate(0, dy);
	}

	m_pDocument->drawContents(&p, event->rect()); //repainting only invalidated area
}


